package com.example.sharingjdbcdemo.sharing;

import com.google.common.collect.Range;
import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;

import java.util.Collection;
import java.util.Properties;
import java.util.stream.Collectors;

/**
 * @ClassName CustomAlgorithm
 * @Description TODO
 * @Author 郭敖
 * @Date 2023年11月05日 12:20
 * @Version 1.0
 */
public class CustomAlgorithm implements StandardShardingAlgorithm<Long> {
    private Properties props = new Properties();

    /**
     * 精确查询走的方法
     * @author 郭敖
     * @date 19:57 2023/11/5
     * @param collection 真实表的表名的集合
     * @param preciseShardingValue 精确查找的值
     * @return 返回真实表的表名
     */
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Long> preciseShardingValue) {
        long i = preciseShardingValue.getValue() % 3;
        String target = "_"+i;
        return collection.stream()
                .filter(tableName -> tableName.endsWith(target))
                .collect(Collectors.toList()).get(0);
    }

    /**
     * 返回的是真实表表名的集合
     * @author 郭敖
     * @date 19:38 2023/11/5
     * @param collection 真实表的表名的集合
     * @param rangeShardingValue between等 范围查找的值
     * @return null
     */
    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Long> rangeShardingValue) {
        String logicTableName = rangeShardingValue.getLogicTableName();
        return collection.stream().filter(tableName -> tableName.startsWith(logicTableName)).collect(Collectors.toList());
    }

    @Override
    public String getType() {
        return "STANDARD_MOD";

    }

    @Override
    public Properties getProps() {
        return this.props;
    }

    public void setProps(Properties props) {
        this.props = props;
    }


    @Override
    public void init(Properties properties) {

    }
}
